package com.lh.item.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lh.common.pojo.PageResult;
import com.lh.item.mapper.BrandMapper;
import com.lh.item.pojo.BrandDo;
import com.lh.item.service.IBrandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 品牌管理
 *
 * @author liuhe
 * @date 2020/06/18
 */
@Service
@Slf4j
public class BrandServiceImpl implements IBrandService {

    final BrandMapper brandMapper;

    @Autowired
    public BrandServiceImpl(BrandMapper brandMapper) {
        this.brandMapper = brandMapper;
    }

    @Override
    public PageResult<BrandDo> queryBrandList(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        // 初始化example对象
        Example example = new Example(BrandDo.class);
        Example.Criteria criteria = example.createCriteria();
        // 根据name模糊查询，或者根据首字母查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%").orEqualTo("letter", key);
        }

        // 添加排序条件
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + " " + (desc ? "desc" : "asc"));
        }

        // 添加分页条件???
        PageHelper.startPage(page, rows);
        List<BrandDo> brandDos = this.brandMapper.selectByExample(example);
        // 包装成pageInfo
        PageInfo<BrandDo> pageInfo = new PageInfo<>(brandDos);
        // 包装成分页结果集返回
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), brandDos);
    }

    @Override
    public boolean saveBrand(BrandDo brandDo, List<Long> cids) {
        int affectRows = this.brandMapper.insert(brandDo);

        cids.forEach((cid) -> {
            this.brandMapper.insertBrandAndCategory(cid, brandDo.getId());
        });
        log.info("saveBrand:{}", affectRows);
        return affectRows >= 1;
    }

    @Override
    public List<BrandDo> queryBrandByCid(Long cid) {
        List<BrandDo> brandDos = this.brandMapper.selectBrandListByCid(cid);
        return brandDos;
    }

    @Override
    public List<BrandDo> queryBrandByBrandIds(List<Long> brandIds) {
        return this.brandMapper.selectByIdList(brandIds);
    }
}
